import produce from 'immer';
import { delay } from 'dva/saga';
/**
 * 排序
 * @param {string} sorter
 */
function sortValue(sorter) {
  if (sorter.order) {
    if (sorter.order === 'ascend') {
      return 'ASC';
    }
    return 'DESC';
  }

  return null;
}

export default function({ namespace, fetchTLService }) {
  return {
    state: {
      tableList: {
        selectedRows: [],
        selectedRowKeys: [],
        list: [],
        pagination: {
          current: 1,
          pageSize: 10,
          total: 0,
        },
        orderBy: {
          property: undefined,
          ordBy: undefined,
        },
      },
      searchForm: {
        defaultValues: {},
        initialValues: {},
        name: namespace,
        expand: false,
        count: 2,
        layout: {
          labelCol: { md: { span: 7 } },
          wrapperCol: { md: { span: 17 } },
        },
        gutter: { md: 8, lg: 24, xl: 48 },
      },
      tab: {
        // tab在请求中的key name
        name: undefined,
        use: false,
        defaultActiveKey: undefined,
        activeKey: undefined,
        list: [],
        selected: {},
      },
    },
    effects: {
      /**
       * 防抖获取列表
       */
      debounceFetchTableList: [
        function*(action, { put }) {
          yield delay(500);
          yield put({
            ...action,
            type: 'fetchTableList',
          });
        },
        { type: 'takeLatest' },
      ],
      /**
       * 获取列表
       */
      fetchTableList: [
        function* fetchTableList({ payload: { service, data } }, { call, put }) {
          const response = yield call(service || fetchTLService, data); // 请求
          const {
            pagerArg: { currentPage, pageSize },
          } = data;
          if (response.success) {
            yield put({
              type: 'updateTableList',
              payload: {
                data: response.data,
                currentPage,
                pageSize,
              },
            });
          }
        },
        { type: 'takeLatest' },
      ],
    },
    reducers: {
      updateTableList: (state, { payload: { data, currentPage, pageSize } }) =>
        produce(state, draft => {
          const list = Array.isArray(data?.pageRecords) ? data.pageRecords : [];
          draft.tableList.list = list;
          draft.tableList.pagination.total = data.totalCount;
          draft.tableList.pagination.current = currentPage;
          draft.tableList.pagination.pageSize = pageSize;
        }),
      toggleTLExpand: state =>
        produce(state, draft => {
          draft.searchForm.expand = !state.searchForm.expand;
        }),
      /**
       * 切换激活tab
       */
      setTabActiveKey: (state, { payload: { activeKey } }) =>
        produce(state, draft => {
          draft.tab.activeKey = activeKey;
          // 因为切换tab公用一个table，所以先清空列表内容
          draft.tableList.list = [];
          draft.tableList.orderBy = {
            property: undefined,
            ordBy: undefined,
          };
        }),
      setTLChange: (state, { payload: { pagination, sorter } }) =>
        produce(state, draft => {
          draft.tableList.pagination = {
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
          };
          draft.tableList.orderBy.property = sorter?.field;
          draft.tableList.orderBy.ordBy = sortValue(sorter);
        }),
      clearTLSelectRow: state =>
        produce(state, draft => {
          draft.tableList.selectedRows = [];
          draft.tableList.selectedRowKeys = [];
        }),
      setTLSelectRow: (state, { payload: { selectedRows, selectedRowKeys } }) =>
        produce(state, draft => {
          draft.tableList.selectedRows = selectedRows;
          draft.tableList.selectedRowKeys = selectedRowKeys;
        }),
      setTLTabList: (state, { payload: { list } }) =>
        produce(state, draft => {
          draft.tab.list = list;
        }),
      setInitialValues: (state, { payload: { initialValues } }) =>
        produce(state, draft => {
          draft.searchForm.initialValues = initialValues;
        }),
    },
  };
}
